<template>
  <div class="publish">
    <van-nav-bar class="publish-header" title="发布" />
    <van-form @submit="onSubmit">
    <!-- 输入任意文本 -->
    <van-field placeholder="请输入标题" v-model="title1" />
    <van-field
      v-model="content"
      class="publish-text"
      rows="2"
      autosize
      type="textarea"
      placeholder="请输入内容"
      show-word-limit
    />
    <van-field
      readonly
      clickable
      :value="value"
      placeholder="请选择分类"
      @click="showPicker = true"
    />
    <van-popup v-model="showPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @cancel="showPicker = false"
        @confirm="onConfirm"
      />
    </van-popup>
<!-- :after-read="uploadQiniu" -->
    <van-uploader name="fileList"  v-model="fileList" multiple />
    <div class="publish-btn">
      <!-- @click="addArticle()" -->
      <van-button type="primary" >确定</van-button>
    </div>
    <div class="home-nav">
      <van-tabbar v-model="active" route>
        <van-tabbar-item icon="home-o" to="/">首页</van-tabbar-item>
        <van-tabbar-item icon="add-o" to="/publish">发布</van-tabbar-item>

        <van-tabbar-item icon="friends-o" to="/my">我的</van-tabbar-item>
      </van-tabbar>
    </div>
    </van-form>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import {uploadQiniu,getToken} from '@/api/api'
import { Toast } from 'vant';
export default {
  data() {
    return {
      fileList: [],
      active: 1,
      value: "",
      showPicker: false,
      columns: [],
      arr: [],
      title1: "",
      content: "",
      cate: "",
      uid_1: "",
      token_1:'',
    };
  },
  computed:{
    // ...mapState(['userInfo'])
  },
  mounted() {
    this.getData();
    this.uid_1 = localStorage.getItem("uid");
    this.token_1 = localStorage.getItem("token");
  },
  methods: {
    getData() {
      this.$http.post("/api/get_cate_list").then((res) => {
        console.log(res);
        this.arr = res.data.data;
        this.arr.forEach((v) => {
          this.columns.push(v.name);
        });
      });
    },
    // addArticle() {
    //   this.$http
    //     .post("/api/add_article", {
    //       title: this.title1,
    //       content: this.content,
    //       cate_name: this.value,
    //       cate_id: this.cate,
    //       author: "1",
    //       author_id: this.uid_1,
    //       imageSrc: this.fileList,
    //     })
    //     .then((res) => {
    //       console.log(res);
    //       console.log(this.fileList)
    //     });
    // },
    onConfirm(value, index) {
      this.value = value;
      this.showPicker = false;
      this.cate = this.arr[index]._id;
      console.log(this.cate);
    },
    
    //上传
    async upload(fileList){
      let imageSrc = []
      if(!fileList || fileList.length === 0){
        //没上传图片
        return imageSrc
      }

      //需要循环
      //多个异步任务都执行完成 返回他们完成后的结果
      let task = this.fileList.map(v=>{
        return new Promise(async (resolve,reject)=>{
          let {file} =v;
          let {type} = file;
          //拿到了类型 比如jpg image/jpg
          type = type.split('/')[1];
          //重新命名 随机名字
          let file_name = `${new Date().getTime()}_${Math.random()
          .toString(36)
          .slice(2)}.${type}`;
          //去服务器申请一个上传token
          let res = await getToken();
          console.log(res.data.token);
          const formdata = new FormData();
          formdata.append('file',file);
          formdata.append('token',res.data.token);
          formdata.append('key',file_name);

         this.$http.post('https://upload-z1.qiniup.com',formdata).then(res=>{
            console.log(res)
            resolve(`http://toutiao.longxiaokj.com/` + res.data.key)
          });


        });
      });


      imageSrc =  await Promise.all(task);
      return imageSrc;
    },
    async onSubmit(){
      // console.log('submit',values);

      //上传图片

      let imageSrc = await this.upload(this.fileList)
      console.log(imageSrc);



      this.$http
        .post("/api/add_article", {
          title: this.title1,
          content: this.content,
          cate_name: this.value,
          cate_id: this.cate,
          author: "1",
          author_id: this.uid_1,
          imageSrc,
        })
        .then((res) => {
          console.log(res);
          // console.log(this.fileList)
          if(res.data.code==0){
            Toast(res.data.msg)
          }else{
            Toast(res.data.msg)
          }
        });

    }

  },
};
</script>

<style lang='less'>
.publish-header {
  background: #07c060;
  .van-nav-bar__title {
    color: white;
  }
}
.publish {
  position: relative;
}

.publish-btn {
  position: absolute;
  left: 13px;
}
.publish-btn button {
  width: 350px;
}
// .publish-text{
//     background: white;
// }

.van-uploader__input {
  text-align: left;
}
</style>